import { RegisterComponent } from "@feng3d/ecs";
import { Color, InstancedMesh, Matrix4 } from "../../thirdparty/three/imports";
import { InstancedBufferAttribute3D } from "../core/InstancedBufferAttribute3D";
import { Mesh3D } from "./Mesh3D";

declare module "@feng3d/ecs"
{
    interface ComponentMap { InstancedMesh3D: InstancedMesh3D; }
}

/**
 * 包装`three`中`Mesh`
 */
@RegisterComponent({ name: 'InstancedMesh3D' })
export class InstancedMesh3D extends Mesh3D
{
    declare _mesh: InstancedMesh;

    get count()
    {
        if (this._mesh)
        {
            this._count = this._mesh.count;
        }

        return this._count;
    }
    set count(v)
    {
        this._count = v;
        if (this._mesh)
        {
            this._mesh.count = this._count;
        }
    }
    private _count: number;

    init()
    {
        this._mesh = new InstancedMesh(this.geometry?._geometry, this.material?._material, this.count);

        super.init();

        this._entity.isInstancedMesh = true;
    }

    destroy(): void
    {
        this._entity.isInstancedMesh = false;

        super.destroy();
    }

    get instanceMatrix()
    {
        const instancedBufferAttribute3D = InstancedBufferAttribute3D.get(this._mesh.instanceMatrix);

        return instancedBufferAttribute3D;
    }

    get instanceColor()
    {
        const instancedBufferAttribute3D = InstancedBufferAttribute3D.get(this._mesh.instanceColor);

        return instancedBufferAttribute3D;
    }

    setMatrixAt(index: number, matrix: Matrix4)
    {
        this._mesh.setMatrixAt(index, matrix);
    }

    setColorAt(index: number, color: Color)
    {
        this._mesh.setColorAt(index, color);
    }

    getColorAt(index: number, color: Color)
    {
        this._mesh.getColorAt(index, color);
    }
}
